package keter.combofs.persist.impl;

import com.alibaba.fastjson.JSONObject;
import keter.combofs.model.ComboFile;
import keter.combofs.model.FileMeta;
import keter.combofs.path.PathMaker;
import keter.combofs.persist.ComboFileDao;
import keter.combofs.persist.Fs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

/**
 * Created by gulx@neusoft.com on 2019/11/11.
 * 使用文件系统存放文件的元数据信息
 */
public class ComboFileDaoFSImpl implements ComboFileDao {

    private static final Logger logger = LoggerFactory.getLogger(ComboFileDaoFSImpl.class);
    @Autowired
    private PathMaker pathMaker;

    @Override
    public void save(ComboFile comboFile) {
        JSONObject r = new JSONObject();
        r.put("id",comboFile. getId());
        r.put("uri",pathMaker.getUri(comboFile.getId()));
        r.put("meta", comboFile.getMeta());
        r.put("created",new Date());
        try {
            logger.info("写入文件元数据:{}",r);
            Fs.save(r);
        } catch (IOException e) {
            logger.error("文件元数据写入异常！", e);
        }
    }

    @Override
    public void addMD5(Long id, String md5) {
        try {
            Fs.addMD5(pathMaker.getUri(id),md5);
        } catch (IOException e) {
            logger.error("文件MD5写入异常！", e);
        }
    }

    @Override
    public ComboFile find(Long id) throws FileNotFoundException {
        JSONObject r;
        try {
            r = Fs.find(pathMaker.getUri(id));
        } catch (IOException e) {
            throw new FileNotFoundException("未找到ID=["+id+"]的文件元数据");
        }
        FileMeta meta = FileMeta.build().set(r.getString("meta"));
        return ComboFile.build(id,r.getString("uri"),meta,null);
    }

    @Override
    public boolean delete(Long id) {
        return Fs.delete(pathMaker.getUri(id));
    }
}